package com.foruo.demo.jdbc;

import com.foruo.demo.jdbc.config.JDBCConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * 数据库jdbc连接工具
 * @author GaoYuan
 */
@Component
public class ConnectionUtils {

    @Autowired
    JDBCConfig jdbcConfig;

    /**
     * 获取连接对象 - 真正创建连接的地方
     * @author GaoYuan
     */
    public Connection getConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUsername(), jdbcConfig.getPassword());
            System.out.println(">>>>>> 创建连接 >>>>>>> " + connection.hashCode());
            return connection;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 这里是真正的释放
     * @author GaoYuan
     */
    public void close(Connection connection, Statement statement, ResultSet resultSet){
        try{
            if(resultSet != null){
                resultSet.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (statement != null) {
                    statement.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if(connection != null){
                    try {
                        connection.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
